import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.Socket;

import utils.StringUtils;

public class SocketHandler implements Runnable {
	
	private Socket socket;
	
	public SocketHandler(Socket socket) {
		this.socket = socket;
	} 

	@Override
	public void run() {
		try {
			// 由Socket对象得到输入流，并构造相应的BufferedReader对象
			BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// 由系统标准输入设备构造BufferedReader对象
			String line = is.readLine();
			while (line != null && !line.equals("bye")) {
				// 如果该字符串为 "bye"，则停止循环
	            
				try {
					if (line.startsWith("openfolder")) {
						String folder = StringUtils.split(line, '?')[1];
						Runtime runtime = Runtime.getRuntime();
		                Process pro = runtime.exec("explorer /e, /select, " + folder);
						
		                pro.waitFor();
					}
					if (line.startsWith("openfile")) {
						String filename = StringUtils.split(line, '?')[1];
						Desktop.getDesktop().open(new File(filename));
					}
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("打开文件/文件夹失败");
				}
	            // 等待执行完成
	            // 从Client读入一字符串，并打印到标准输出上
				line = is.readLine();
			}
			is.close(); // 关闭Socket输入流
			socket.close(); // 关闭Socket
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
